package com.gxa.autoparts.portal.service.impl;

import com.gxa.autoparts.core.pojo.Goods;
import com.gxa.autoparts.portal.service.GoodService;
import com.gxa.autoparts.portal.service.UserBrowseRecordsService;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;

import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

@Service
public class UserBrowseRecordsServiceImpl implements UserBrowseRecordsService {

    private static final String KEY_HISTORY="keyHistory:";

    @Autowired
    GoodService goodService=null;

    @Autowired
    RedisTemplate<String,Object> redisTemplate=null;




    @Override
    public List<Goods> findAll(Long userId) throws URISyntaxException {

        List<Goods> list = new ArrayList<>();
        // 获取用户最近浏览的SkuId
        Set<Object> objects = redisTemplate.opsForZSet().reverseRange(KEY_HISTORY + userId, 0, 9);
        for (Object object : objects) {
            Goods goods = goodService.searchGoodById(Long.valueOf(object.toString()));

            list.add(goods);
        }

        return list;
    }

    @Override
    public void update(Long userId,List<Long> list) {

        for (Long aLong : list) {
            ZSetOperations<String, Object> zSetOperations = redisTemplate.opsForZSet();
//        //zset内部是按分数来排序的，这里用当前时间做分数
            zSetOperations.remove(KEY_HISTORY + userId, aLong);
        }

    }

    @Override
    public void add(Long userId,Long goodsId) {
        ZSetOperations<String, Object> zSetOperations = redisTemplate.opsForZSet();
//        //zset内部是按分数来排序的，这里用当前时间做分数
        zSetOperations.add(KEY_HISTORY + userId, goodsId, System.currentTimeMillis());
//          例子: 只保留5个元素
//        //环形结构 -6, -5, -4, -3, -2, -1 (负数索引)
//                          0 ,  1 ,   2 , 3  , 4,  5 (正数索引)
//         只要5个元素, 移除0 ~ -6之间的元素,只保留-1~ -5元素
        // 保留10个skuId
        zSetOperations.removeRange(KEY_HISTORY + userId, 0, -11);


    }
}
